package com.pb.infra.oth.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http请求
 *
 * @author liudebao
 * @date 2020/2/27
 */
@Slf4j
public class HttpClientUtil {
    private HttpClientUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * get请求
     *
     * @param url
     * @param paramMap
     */
    public static String requestGet(String url, Map<String, String> paramMap) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            StringBuilder param = new StringBuilder();
            int i = 0;
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                if (i == 0) {
                    param.append("?");
                } else {
                    param.append("&");
                }
                param.append(entry.getKey() + "=" + entry.getValue());
                i++;
            }
            try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            log.error("Failed to requestGet", e);
            return null;
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param paramMap
     */
    public static String requestPost(String url, Map<String, String> paramMap) {
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpPost post = new HttpPost(url);
            List<NameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
            try (CloseableHttpResponse response = client.execute(post)) {
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            log.error("Failed to requestPost", e);
            return null;
        }
    }
}